<template>
  <div v-loading="loading">
    <div class="pub-detail-title-btn">
      <template v-if="state !== 3">
        <a-button
          type="primary"
          @click="openDailog"
        >
          添加行
        </a-button>
        <a-button @click="handleDel">
          删除行
        </a-button>
        <!-- <a-button>
                    导出模板
                </a-button>
                <a-button>
                    导入
                </a-button> -->
      </template>
      <excel
        ref="exportSelect"
        file-name="调拨明细"
        is-click-generate="false"
      >
        <a-button
          slot="excelBtn"
          @click="exportSelect"
        >
          导出选中
        </a-button>
      </excel>
      <excel
        ref="exportAll"
        file-name="调拨明细"
        is-click-generate="false"
      >
        <a-button
          slot="excelBtn"
          @click="exportAll"
        >
          导出全部
        </a-button>
      </excel>
    </div>
    <a-table
      ref="table"
      :pagination="false"
      :columns="columns"
      :data-source="data"
      bordered
      class="bgFFF"
      :scroll="{ x: 1300 }"
      row-key="id"
      :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
    >
      <span
        slot="index"
        slot-scope="text, record, index"
      >{{ index + 1 }}</span>
      <template
        v-for="col in ['estSize', 'actTransferSize', 'lastSize', 'estUnitPrice', 'amount', 'remark']"
        :slot="col"
        slot-scope="text, record"
      >
        <div :key="col">
          <template v-if="state != 3">
            <BaseInput
              v-if="col === 'remark'"
              :value="text"
              :disabled="
                col === 'estSize' || col === 'lastSize' || col === 'estUnitPrice' || col === 'amount'
              "
              @blur="(e) => handleChange(e.target.value, record.id, col)"
            />
            <BaseInputNumber
              v-else-if="col === 'estSize' || col === 'actTransferSize'"
              v-model="record[col]"
              class="form-item"
              :precision="3"
              :disabled="col === 'estSize'"
              @blur="(e) => handleChange(e.target.value, record.id, col)"
            />
            <BaseInputNumber
              v-else-if="col === 'estUnitPrice' || col === 'amount'"
              :precision="2"
              :value="text"
              :disabled="
                col === 'estSize' || col === 'lastSize' || col === 'estUnitPrice' || col === 'amount'
              "
              @blur="(e) => handleChange(e.target.value, record.id, col)"
            />
            <BaseInputNumber
              v-else
              :precision="2"
              :value="text"
              :disabled="
                col === 'estSize' || col === 'lastSize' || col === 'estUnitPrice' || col === 'amount'
              "
              @blur="(e) => handleChange(e.target.value, record.id, col)"
            />
          </template>
          <template v-else>
            {{ text }}
          </template>
        </div>
      </template>
    </a-table>
    <pagination
      v-model="pageNo"
      :total="totalSize"
      :page-size.sync="pageSize"
      @change="handlePageChange"
      @showSizeChange="showSizeChange"
    />
    <!-- 物料选择 -->
    <materialListAndDir
      ref="detailDialog"
      mode="single"
      :api="disposalDetailList"
      :local-columns="materialListColumns"
      :local-search-arr="materialListSearchArr"
      row-key="materialCode"
      :request-params="{ disposalApplyId: disposalApplyId }"
      :row-config="{ key: 'materialCode', name: 'materialName' }"
      @createList="createList"
    />
  </div>
</template>
<script>
import {
    transfersDetailList,
    transfersDetailDel,
    transfersDetailEdit,
    transfersDetailAddBatch
} from '@/api/material/remaining/transfers'
import { columns } from './insideModel'
import { disposalDetailList } from '@/api/material/remaining/disposal'
import materialListAndDir from '@/components/materialListAndDir/materialListAndDir'

const data = []
export default {
    // name:'a'+Date.now(),
    components: {
        materialListAndDir
    },
    props: {
        state: {
            type: Number
        },
        id: {
            type: String
        },
        disposalApplyId: {
            type: String
        }
    },
    data() {
        this.cacheData = data.map((item) => ({ ...item }))
        return {
            loading: false,
            selectedRows: [],
            pageNo: 1,
            pageSize: 10,
            queryParam: {},
            totalSize: 0,
            selectedRowKeys: [],
            columns: columns,
            editingKey: '',
            data: [],
            optionArr: [],
            selectedId: [],
            mainTermsId: null,
            employeeName: '',
            rules: {
                // estSize: [{ rule: 'required', message: '应拨数量不能为空' }],
                actTransferSize: [{ rule: 'required', message: '实拨数量不能为空' }]
            },
            disposalDetailList: disposalDetailList,
            materialListSearchArr: [
                {
                    name: '物料名称',
                    value: 'name',
                    type: 'input'
                },
                {
                    name: '物料编码',
                    value: 'key',
                    type: 'input'
                },

                {
                    name: '规格型号',
                    value: 'specificationModel',
                    type: 'input'
                }
            ],
            materialListColumns: [
                {
                    title: '序号',
                    customRender() {
                        return arguments[2] + 1
                    }
                },
                {
                    title: '物料名称',
                    dataIndex: 'materialName'
                },
                {
                    title: '物料编码',
                    dataIndex: 'materialCode'
                },
                {
                    title: '规格型号',
                    dataIndex: 'materialModel'
                },
                {
                    title: '单位',
                    dataIndex: 'materialUnit'
                }
            ]
        }
    },
    mounted: function () {
        if (this.state === 3) {
            this.editingKey = true
        }
        this.list()
        this.initErrMessage(this.rules)
        this.$refs.exportSelect.tableToExcelFile(this.$refs.table)
        this.$refs.exportAll.tableToExcelFile(this.$refs.table)
    },
    methods: {
        /**
         * @description: 获取全部列表
         */
        async getAll(callback, errorCallback) {
            let total = this.totalSize
            console.log(total)
            if (total > 0) {
                let res = await transfersDetailList({
                    pageSize: this.totalSize,
                    pageNo: 1,
                    baseId: this.id
                })
                if (res.code !== this.SUCCESS_CODE) {
                    errorCallback && errorCallback(res)
                    return
                } else {
                    callback && callback(res)
                }
            } else {
                callback && callback({ data: [] })
            }
        },
        exportSelect: function () {
            if (this.selectedRowKeys.length > 0) {
                this.$refs.exportSelect.setDataAndGenerate(this.selectedRows)
            } else {
                this.$message.warning('请选择需要导出的数据')
            }
        },
        exportAll: function () {
            // 参数：查询条件、导出的回调
            if (this.totalSize) {
                this.pageNo = 1
                this.list(this.$refs.exportAll.setDataAndGenerate)
            } else {
                this.$message.warning('没有可导出的数据')
            }
        },
        openDailog: function () {
            if (this.editingKey !== '') {
                this.$message.warning('新增前请结束当前操作行')
                return
            }
            this.getAll((res) => {
                this.$refs.detailDialog.open(res.data)
            })
        },
        createList: function (selectRows) {
            let _this = this
            let form = selectRows.map((selectRow) => ({
                materialName: selectRow.materialName,
                materialCode: selectRow.materialCode,
                materialModel: selectRow.materialModel,
                materialUnit: selectRow.materialUnit,
                disposalDetailsId: selectRow.id,
                transferId: this.id,
                estSize: 0,
                actTransferSize: 0,
                lastSize: 0,
                estUnitPrice: 0,
                amount: 0,
                remark: ''
            }))

            transfersDetailAddBatch(form).then((res) => {
                if (res.code === 200) {
                    _this.list()
                }
            })
        },
        // 删除
        handleDel() {
            this.$confirm({
                title: '确定是否删除数据？',
                okText: '是',
                okType: 'danger',
                cancelText: '否',
                onOk: () => {
                    return transfersDetailDel({ ids: this.selectedId }).then((res) => {
                        if (res.data.code === 200) {
                            this.initTable()
                            this.selectedId = []
                            this.selectedRowKeys = []
                            this.selectedRows = []
                            this.editingKey = ''
                            this.$message.success('删除成功！')
                        }
                    })
                }
            })
        },
        initTable() {
            this.pageNo = 1
            this.list()
        },
        list(callback) {
            this.loading = true
            let _this = this
            transfersDetailList({
                pageSize: callback ? _this.totalSize : _this.pageSize,
                pageNo: _this.pageNo,
                baseId: _this.id
            }).then((res) => {
                if (res.code === 200) {
                    if (callback) {
                        if (res.data.length) {
                            callback(res.data)
                        } else {
                            this.$message.warning('没有可导出的数据')
                        }
                        this.loading = false
                        return
                    }
                    _this.data = res.data
                    _this.totalSize = res.totalSize
                    this.cacheData = res.data.map((item) => ({ ...item }))
                }
                this.loading = false
            })
        },
        handleChange(value, key, column) {
            const newData = [...this.data]
            const target = newData.filter((item) => key === item.id)[0]
            if (target) {
                target[column] = value
                if (target['actTransferSize'] > target['estSize']) {
                    this.$message.warning('实拨数量不能大于应拨数量')
                    target['actTransferSize'] = null
                    return
                }
                target['lastSize'] = target['estSize'] - target['actTransferSize']
                target['lastSize'] = target['lastSize'].toFixed(2)
                target['amount'] = target['actTransferSize'] * target['estUnitPrice']
                target['amount'] = target['amount'].toFixed(2)
                if (this.rules[column]) {
                    this.customValidation(value, column)
                }
                this.data = newData
            }
            this.save(key)
        },
        edit(key) {
            const newData = [...this.data]
            const target = newData.filter((item) => key === item.id)[0]
            this.editingKey = key
            if (target) {
                target.editable = true
                this.mainTermsId = target.mainTermsId
                this.employeeName = target.employeeName
                this.data = newData
            }
        },
        handlePageChange(pageNo, pageSize) {
            this.pageNo = pageNo
            this.list()
            this.selectedRowKeys = []
        },
        showSizeChange(pageNo, pageSize) {
            this.pageSize = pageSize
            this.initTable()
        },
        save(key) {
            // 编辑保存
            const newData = [...this.data]
            const newCacheData = [...this.cacheData]
            const target = newData.filter((item) => key === item.id)[0]
            for (let key in target) {
                if (this.rules[key]) {
                    this.customValidation(target[key], key)
                }
            }
            for (let i in this.customValidationErr) {
                if (i) {
                    return
                }
            }
            // this.loading = true
            target.transferId = this.id
            transfersDetailEdit(target).then((res) => {
                if (res.code === 200) {
                    this.$message.success('保存成功')
                    // this.initTable()
                }
                // this.loading = false
            })
            const targetCache = newCacheData.filter((item) => key === item.id)[0]
            if (target && targetCache) {
                delete target.editable
                this.data = newData
                Object.assign(targetCache, target)
                this.cacheData = newCacheData
            }
            this.editingKey = ''
        },
        onSelectChange(selectedRowKeys, selectedRows) {
            this.selectedId = []
            selectedRows.map((i) => {
                this.selectedId.push(i.id)
            })
            this.selectedRowKeys = selectedRowKeys
            this.selectedRows = selectedRows
        },
        cancel(key) {
            const newData = [...this.data]
            const target = newData.filter((item) => key === item.id)[0]
            this.editingKey = ''
            if (target) {
                if (target.isAdd) {
                    newData.splice(0, 1)
                } else {
                    Object.assign(target, this.cacheData.filter((item) => key === item.id)[0])
                    target.editable = false
                    delete target.editable
                }
                this.data = newData
            }
        }
    }
}
</script>

<style lang="less" scoped>
/deep/ .form-item {
    .ant-input:not([disabled]),
    .ant-time-picker-input,
    .ant-select:not(.ant-select-disabled) .ant-select-selection,
    .ant-calendar-picker-input,
    .ant-input-number-input:not([disabled]),
    .ant-cascader-picker {
        border-color: #e4ac0b;
        background-color: #fff9e8;
    }
}
</style>